package com.young.application.facade.impl;

import com.young.application.facade.CashierService;
import com.young.domain.entity.CashierModel;
import com.young.domain.repository.OrderRepository;
import com.young.infrastructure.event.AcceptEvent;
import com.young.infrastructure.po.Order;
import com.young.infrastructure.client.RiskService;
import com.young.application.convertor.CashierConverter;
import com.young.api.response.RiskConsultResponse;
import com.young.api.sdo.CashierSubmitRequestSDO;
import com.young.api.sdo.CashierSubmitResponseSDO;
import com.young.infrastructure.publisher.AcceptEventPublisher;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class CashierServiceImpl implements CashierService {
    @Resource
    private CashierConverter cashierConverter;
    @Autowired
    private RiskService riskService;
    @Autowired
    private OrderRepository orderRepository;
    @Autowired
    private AcceptEventPublisher acceptEventPublisher;

    @Override
    public CashierSubmitResponseSDO submit(CashierSubmitRequestSDO cashierSubmitRequestSDO) {
        CashierModel cashierModel = cashierConverter.cashierSubmitRequestSDO2Model(cashierSubmitRequestSDO);
        //初始化orderNo，提交阶段orderNo和externalNo都可以为空
        cashierModel.initOrderNo(cashierSubmitRequestSDO.getOrderNo(),cashierSubmitRequestSDO.getExternalNo());

        //调用风控服务获取风控信息
        RiskConsultResponse response = riskService.consultRisk();
        if (response.isFail()){
            CashierSubmitResponseSDO cashierSubmitResponseSDO=new CashierSubmitResponseSDO();
            cashierSubmitResponseSDO.setCode(400);
            cashierSubmitResponseSDO.setMsg("操作失败");
            return cashierSubmitResponseSDO;
        }

        //获取风控咨询结果成功
        cashierModel.updateRiskStatus(response.getRiskData());

        //存储order数据
        Order order=cashierConverter.model2OrderDo(cashierModel);
        Boolean save = orderRepository.save(order);
        if (save){
            //保存成功,发送消息
            if (cashierModel.passRisk()){
                AcceptEvent acceptEvent=new AcceptEvent(cashierModel);
                acceptEventPublisher.publish(acceptEvent);
            }
            return cashierConverter.cashierModel2CashierSubmitResponseSDO(cashierModel);
        }
        CashierSubmitResponseSDO cashierSubmitResponseSDO=new CashierSubmitResponseSDO();
        cashierSubmitResponseSDO.setCode(400);
        cashierSubmitResponseSDO.setMsg("保存失败");
        return cashierSubmitResponseSDO;
    }
}
